#include<stdio.h>
#include<fcntl.h>
#include<unistd.h>
#include<stdlib.h>
#include<string.h>
#include<sys/types.h>

#define SIZE_1M 1024*1024
#define SIZE_10M 10*1024*1024

//系统IO拷贝文件
int main(int argc, char const *argv[])
{
    if(argc != 3){
        printf("Usage: %s <src源文件> <dst目标文件>\n", argv[0]);
        return -1;
    }

    int fd1 = open(argv[1], O_RDONLY);
    if(fd1 == -1){
        perror("源文件打开失败!");
        return -1;
    }
    
    int fd2 = open(argv[2], O_WRONLY | O_CREAT | O_TRUNC, 0644);
    if(fd2 == -1){
        perror("目标文件打开失败!");
        return -1;
    }

    lseek(fd1, 0, SEEK_END);
    long len = lseek(fd1, 0, SEEK_CUR) / 10;
    lseek(fd1, 0, SEEK_SET);

    char *buf = malloc(len); 
    while(1){  
        int ret = read(fd1, buf, len); //实际读取的字数
        if(ret == -1){
            perror("读文件失败！");
            return -1;
        }
        if(ret == 0){
            printf("拷贝完成!\n");
            break;
        }
        //正常读到ret个字节
        if(ret > 0){
            //将ret个字节写入fd2
            int total = 0;
            while(ret > 0){
                int m = write(fd2, buf + total, ret); //实际写入的字数
                if(m < 0){
                    perror("写文件失败！");
                    return -1;
                }
                ret -= m;
                total += m;
            }
        }
    }
    close(fd1);
    close(fd2);
    free(buf);
    return 0;
}
